package com.wissen.temperatureapp.client.controller;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.wissen.temperatureapp.client.observers.TemperatureObserver;
import com.wissen.temperatureapp.client.services.TemperatureService;
import com.wissen.temperatureapp.client.services.TemperatureServiceAsync;

/**
 * Class represents a controller part of MVC. Its acts as a Mediator to
 * application.
 * 
 * @author Mayur Birari
 */
public class TempController {

	/**
	 * Create a remote service proxy to talk to the server-side converter
	 * service.
	 */
	private final TemperatureServiceAsync tempService = GWT
			.create(TemperatureService.class);
	private static TempController _instance;

	private TempController() {
	}

	public static synchronized TempController getInstance() {
		if (_instance == null) {
			_instance = new TempController();
		}
		return _instance;
	}

	public TemperatureServiceAsync gettempService() {
		return tempService;
	}

	// ---------------------- Observers -------------------------------
	private List<TemperatureObserver> tempObservers = new ArrayList<TemperatureObserver>();

	// --------------- Registration/DeRegitration methods --------------
	public void addTempObserver(TemperatureObserver observer) {
		tempObservers.add(observer);
	}

	public void removeTempObserver(TemperatureObserver observer) {
		tempObservers.remove(observer);
	}

	// ---------------------- Controller's Methods ---------------------
	public void convertTemp(double celsius) {
		tempService.convertTemp(celsius,tempCallback);
	}

	// -------------------- Call Back classes ---------------------------
	AsyncCallback<Double> tempCallback = new AsyncCallback<Double>() {
		@Override
		public void onFailure(Throwable caught) {
			GWT.log("Error in conversion ", caught);
			for (TemperatureObserver observer : tempObservers) {
				observer.notifyConvertFailed("conversion failed: " + caught);
			}
		}

		@Override
		public void onSuccess(Double isValid) {
			
			/*if (isValid.isNaN()) {*/
				for (TemperatureObserver observer : tempObservers) {
					observer.notifyConvertSucceeded(isValid);
			} /*else {
				for (TemperatureObserver observer : tempObservers) {
					observer.notifyConvertFailed("Invalid Celsius value ");
				}*/
		}
	};

}
